package com.desire.test;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * 三人吃饭, 都到达才开始吃饭
 *
 * @author desire
 */
public class _42_CyclicBarrier_循环栅栏 {
    // parties 等待的线程数量  barrierAction 线程最后执行的语句
    CyclicBarrier bar = new CyclicBarrier(3, () -> System.out.println("大家到起了，开饭了."));

    public static void main(String[] args) {
        var t = new _42_CyclicBarrier_循环栅栏();
        new Thread(() -> t.eat(6), "李四").start();
        new Thread(() -> t.eat(2), "张三丰").start();
        new Thread(() -> t.eat(12), "赵六").start();
    }

    public void eat(int time) {
        System.out.println(Thread.currentThread().getName() + "开始动身...");
        try {
            TimeUnit.SECONDS.sleep(time);
            System.out.println(Thread.currentThread().getName() + "到达。");
            bar.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}
